class RateCLI
  module Show

    def download(target, to_download)

      path = nil
      loop do
        path = @sui.ask "Download to:"
        break if File.directory?(path) || File.directory?(File.dirname(path))
        error "No such file or directory: #{path}"
      end

      result = @client.download(target: target, uuid: to_download['uuid'], path: path)

      if not result
        error "can' download #{target}: #{result.message}"
      else
        success "downloaded #{target} to #{path}"
      end
      
    end

    def show_view(view)
      puts hash2table(view)
    end

    def show_benchmark(benchmark)
      puts hash2table(benchmark)
    end

    def update(target, to_update)
      update_params = {}
      to_update.each do |key, val|
        next if key.include?('uuid') || ['created', 'updated', 'type', 'protocal'].include?(key)
        ans = @sui.ask "change #{Rainbow(key).bright} to? Press Enter if not change (#{val}):"
        if ans != ''
          update_params[key] = ans
        end
      end
      puts hash2table(update_params)
      yes = @sui.ask_yes_no 'Sure?'

      if yes
        @client.update(update_params.merge(target: target, uuid: to_update['uuid']))
      end
    end

    def show(target, to_show)
      if target == 'task'
        to_show['url'] = "http://#{@client.host}:4567/tasks/#{to_show['uuid']}"
      end

      r = false

      loop do
        puts hash2table(to_show)

        question = '[u]pdate'

        if target == 'benchmark' || target == 'task'
          question << " | [d]ownload | [i]mages"
        end

        if target == 'task'
          question << " | [o]oen in browser"
        end

        question << " | any other key to go back:"

        ans = @sui.ask question

        case ans
        when 'd' then download(target, to_show)
        when 'i' then
          download('image', to_show) if target == 'benchmark'
        when 'o' then
          Launchy.open(to_show['url']) if target == 'task'
        when 'u' then 
          update(target, to_show)
          r = true
        else break
        end
      end

      return r
    end
  end
end